package com.wzq.controller.pc;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wzq.controller.admin.GetSome;
import com.wzq.dao.dto.MemberDto;
import com.wzq.dao.pojo.*;
import com.wzq.exception.GlobleExceptionHandler;
import com.wzq.service.IMemberService;
import com.wzq.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/PC/member")
public class PCMemberController extends GetSome {

    //   添加
    @PostMapping
    public Result save(@RequestBody Member member) {
        LambdaQueryWrapper<Message> lqw = new LambdaQueryWrapper();
        lqw.eq(Message::getType,3).eq(Message::getIsdelete,0).eq(Message::getIsread,0);
        lqw.eq(Message::getW_id,member.getW_id()).eq(Message::getP_id,member.getP_id());
        if (super.iMessageService.getOne(lqw)!=null)
            return new Result(Code.SAVE_ERR,null,"已申请");
        boolean flag = iMemberService.save(member);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    //   创建活动时
    @PostMapping("/{w_id}/add/{p_id}")
    public Result save(@RequestBody List<String>[] lists,@PathVariable Integer p_id,@PathVariable Integer w_id) {
        boolean flag=true;
        List<Member> members =new ArrayList<>();
//        添加创建者
        Member member1 = new Member();
        member1.setW_id(w_id);
        member1.setP_id(p_id);
        member1.setIdentities(0);
        member1.setIsaccpt(1);
        members.add(member1);
//      添加 成果归属成员
        for (String id : lists[0])
        {
            Member member = new Member();
            member.setW_id(Integer.valueOf(id));
            member.setP_id(p_id);
            member.setIdentities(2);
            members.add(member);
        }
//        添加普通成员
        lists[1].removeAll(lists[0]);
        for (String id : lists[1]){
            Member member = new Member();
            member.setW_id(Integer.valueOf(id));
            member.setP_id(p_id);
            member.setIdentities(1);
            members.add(member);
        }
        for (Member m : members){
            flag = iMemberService.save(m);
        }
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    @GetMapping("/select")
    public Result selectApp(@RequestBody List<Member> members,@RequestParam("like") String like) {
        ArrayList<Member> memberslist = new ArrayList<>();
        String pattern= "*"+like+"*";
        for (Member member : members) {
            if (Pattern.matches(pattern, member.getP_name()));
            memberslist.add(member);
        }
        return new Result(Code.GET_OK,memberslist,"true");
    }

    //添加创建者成员
    @GetMapping("/AddmMember")
    public Result AddmMember(@RequestParam("w_id") String w_id ,@RequestParam("p_id") String p_id){
        System.out.println(w_id + p_id);
        int i = iMemberService.AddmMember(w_id,p_id);
        if (i>0){
            return new Result(Code.SAVE_OK,"创建者插入成功");
        }
        return new Result(Code.SAVE_ERR,"创建者插入失败");
    }

    //根据项目ID查询该项目下的成员信息
    @PostMapping("/SelectMenberByPid/{p_id}")
    public Result SelectMenberByPid(@PathVariable Integer p_id){
        Map<String, Object> map = new HashMap<>();
        // 创建者
        Member member=new Member();
        // 成员
        ArrayList<Member> members = new ArrayList<>();
        // LQW
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper();
        lqw.eq(Member::getP_id,p_id).eq(Member::getIsaccpt,1);
        try {
            List<Member> list = iMemberService.list(lqw);
            for (Member m : list ) {
                m.setW_name(getW_name(m.getW_id()));
                m.setAvatarUrl(getAvatarUrl(m.getW_id()));
                m.setSys_number(getsys_number(m.getW_id()));
                if (m.getIdentities()==1)
                    members.add(m);
                else
                    member =m;
            }
        } catch (Exception e){
            new GlobleExceptionHandler().exceptionHandler(null,e);
        }

        map.put("member", member);
        map.put("members", members);
        if (map.isEmpty()){
            return new Result(Code.GET_ERR,false,"查询失败");
        }
        return new Result(Code.GET_OK,map,"查询成功");
    }
    // 接受
    @PutMapping("/{w_id}/accpt/{p_id}/read/{m_id}")
    public Result accpt(@PathVariable Integer w_id, @PathVariable Integer p_id, @PathVariable Integer m_id) {
        //  接受邀请
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper();
        lqw.eq(Member::getW_id,w_id).eq(Member::getP_id,p_id);
        Member member = iMemberService.getOne(lqw);
        member.setIsaccpt(1);
        boolean flag = iMemberService.updateById(member);
        //  已读
        Message message = iMessageService.getById(m_id);
        message.setIsread(1);
        message.setOperation(1);
        //  回复发送方
        Message message1 = new Message();
        message1.setW_id(w_id);
        message1.setW_id_down(message.getW_id());
        message1.setP_id(p_id);
        message1.setType(10);
        message1.setName(getW_name(w_id));
        iMessageService.save(message1);
        boolean flag2 = iMessageService.updateById(message);
        return new Result(flag && flag2 ? Code.UPDATE_OK:Code.UPDATE_ERR,flag && flag2);
    }
    // 已读
    @PutMapping("/read/{m_id}")
    public Result read(@PathVariable Integer m_id) {
        //  已读
        Message message = iMessageService.getById(m_id);
        message.setIsread(1);
        boolean flag = iMessageService.updateById(message);
        return new Result(flag  ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    //   拒绝
    @DeleteMapping("/{w_id}/unaccpt/{p_id}/read/{m_id}")
    public Result unaccpt(@PathVariable Integer w_id, @PathVariable Integer p_id, @PathVariable Integer m_id) {
        //  修改消息删除标记
        Message message = iMessageService.getById(m_id);
        message.setIsread(1);
        message.setOperation(2);
        message.setIsdelete(1);
        boolean flag = iMessageService.updateById(message);
        // 拒绝加入
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper();
        lqw.eq(Member::getW_id,w_id).eq(Member::getP_id,p_id);
        Member one = iMemberService.getOne(lqw);
        iMemberService.removeById(one.getId());
        //  回复发送方
        Message message1 = new Message();
        message1.setW_id(w_id);
        message1.setW_id_down(message.getW_id());
        message1.setP_id(p_id);
        message1.setType(11);
        message1.setName(getW_name(w_id));
        boolean flag2 = iMemberService.remove(lqw);
        return new Result(flag && flag2 ? Code.UPDATE_OK:Code.UPDATE_ERR,flag && flag2);
    }
    //   清空已读消息
    @DeleteMapping("/clear/{w_id}")
    public Result clear(@PathVariable Integer w_id) {
        LambdaUpdateWrapper<Message> luw = new LambdaUpdateWrapper();
        luw.eq(Message::getW_id_down,w_id).eq(Message::getIsread,1).set(Message::getIsdelete,1);
        //  修改消息删除标记
        return new Result(iMessageService.update(luw) ? Code.UPDATE_OK:Code.UPDATE_ERR,null);
    }

    //   申请加入
    @PostMapping("/Applyjoin")
    public Result Applyjoin(@RequestBody Member member) {
        Project one = iProjectService.getOne(new LambdaQueryWrapper<Project>().eq(Project::getId,member.getP_id()));
        if (one == null)
            return new Result(Code.SAVE_ERR,false);
        if (one.getAuthor() == member.getW_id())   member.setIdentities(0);
        else member.setIdentities(1);
        boolean flag = iMemberService.save(member);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    //     获得申请状态
    @PostMapping("/state")
    public Result getState(@RequestBody Member member)  {
        System.out.println(member.getP_id());
        Member m = iMemberService.getOne(new LambdaQueryWrapper<Member>()
                .eq(Member::getW_id,member.getW_id()).eq(Member::getP_id,member.getP_id()));
        if (m==null)
            return new Result(Code.GET_ERR,404);
        return new Result(Code.GET_OK,m.getIsaccpt(),"申请状态");
    }
    //     获得申请理由
    @GetMapping("/app/{w_id}")
    public Result getById(@PathVariable Integer w_id) throws Exception {
        isover();
        List<Member> active = new ArrayList<>();
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Member::getW_id,w_id);
        List<Member> list = iMemberService.list(lqw);
        for (Member member : list) {
            Project byId = iProjectService.getById(member.getP_id());
            if (byId.getIsover()==0) {
                member.setP_name(getP_name(member.getP_id()));
                active.add(member);
            }
        }
        Integer code = active != null ? Code.GET_OK : Code.GET_ERR;
        String msg = active != null ? "" : "数据查询失败，请重试！";
        return new Result(code,active,msg);
    }

    @PostMapping("/IsApply")
    public Result IsApply(@RequestBody Member member){
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getId,member.getP_id());
        wrapper.eq(Project::getApply,0);
        Project one = iProjectService.getOne(wrapper);
        if (one != null){
            return new Result(Code.GET_ERR,"不允许加入");
        }
        LambdaQueryWrapper<Message> lqw = new LambdaQueryWrapper();
        lqw.eq(Message::getType,3).eq(Message::getIsdelete,0).eq(Message::getIsread,0);
        lqw.eq(Message::getW_id,member.getW_id()).eq(Message::getP_id,member.getP_id());
        if (super.iMessageService.getOne(lqw)!=null)
            return new Result(Code.SAVE_ERR,null,"已申请");
        return new Result(Code.SAVE_OK,null,"未申请");
    }

    //   修改
    @PutMapping
    public Result update(@RequestBody Member member) {
        boolean flag = iMemberService.updateById(member);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    //    删除
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id ) {
        boolean flag = iMemberService.removeById(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    //    删除多个id对应用户
    @DeleteMapping
    public Result deleteById(@RequestBody List<Integer> ids) {
        boolean flag = iMemberService.removeByIds(ids);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    //     获得所有成员
    @GetMapping
    public Result getAll() {
        List<Member> list = iMemberService.list();
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }
}

